package com.shimao.celnet.payment.util;

import com.shimao.celnet.payment.model.IInterfaceLog;
import com.shimao.celnet.payment.service.IAppService;
import com.shimao.celnet.payment.service.IInterfaceLogService;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.TreeMap;

/**
 * 公共post请求类，用于发送post请求
 */
@Service
public class HttpSendPostUtil {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired//接口日志Service
    private IInterfaceLogService interfaceLogService;
    @Autowired
    private IAppService iAppService;

    /**
     * 向指定 URL 发送POST请求的方法
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public String sendPost(String url, JSONObject params, String token, String appKey, String interfaceid) {
        logger.info("=================推送开始============");
        PrintWriter out = null;
        BufferedReader in = null;
        long startTimeMillis = 0; // 开始时间
        long endTimeMillis = 0; // 结束时间
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("token", token);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            startTimeMillis = System.currentTimeMillis();
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            // 发送请求参数
            logger.info("推送请求参数："+params.toString());
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                    result += line;
            }
            endTimeMillis = System.currentTimeMillis();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        this.saveLogger(url, params, token, result, startTimeMillis, endTimeMillis,appKey,interfaceid);
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public String sendPost(String url, JSONObject params, String appKey, String interfaceid) {
        logger.info("=================推送开始============");
        TreeMap<String,String> headers = new TreeMap<String,String>();
        PrintWriter out = null;
        BufferedReader in = null;
        String timestamp = null;
        String sign = null;
        String token = iAppService.getAppTokenByAppkey(appKey);
        long startTimeMillis = 0; // 开始时间
        long endTimeMillis = 0; // 结束时间
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            //设置通用的请求属性
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            headers.put(FinalUtil.HEADER_CONTENT_TYPE,"application/json;charset=utf-8");
            if(params.getString("paymentId") == null||"".equals(params.getString("paymentId"))){
                headers.put(FinalUtil.HEADER_METHOD,"invOpenRetInfoOut");
                conn.setRequestProperty("method", "invOpenRetInfoOut");
                headers.put(FinalUtil.HEADER_INTERFACE_ID,"164");
                conn.setRequestProperty("integration_id", "164");
            }else {
                headers.put(FinalUtil.HEADER_METHOD,"outPayRetInfoOut");
                conn.setRequestProperty("method", "outPayRetInfoOut");
                headers.put(FinalUtil.HEADER_INTERFACE_ID,"141");
                conn.setRequestProperty("integration_id", "141");
            }
            headers.put(FinalUtil.HEADER_APP_KEY,appKey);
            conn.setRequestProperty("app_key", appKey);
            headers.put(FinalUtil.HEADER_TIMESTAMP,String.valueOf(MyDateUtil.DateToStr(new Date(), MyDateUtil.formatDefaultTimestamp)));
            conn.setRequestProperty("timestamp", headers.get(FinalUtil.HEADER_TIMESTAMP));
            sign = mySign(headers,token);
            conn.setRequestProperty("sign", sign);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            startTimeMillis = System.currentTimeMillis();
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            logger.info("推送请求参数："+params.toString());
            // 发送请求参数
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            endTimeMillis = System.currentTimeMillis();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            logger.info("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        this.saveLogger(url, params, "", result, startTimeMillis, endTimeMillis,appKey,interfaceid);
        return result;
    }

    /**
     * 开票结果通知向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public String sendPost1(String url, JSONObject params, String appKey, String interfaceid) {
        logger.info("=================推送开始============");
        TreeMap<String,String> headers = new TreeMap<String,String>();
        PrintWriter out = null;
        BufferedReader in = null;
        String timestamp = null;
        String sign = null;
        String token = iAppService.getAppTokenByAppkey(appKey);
        long startTimeMillis = 0; // 开始时间
        long endTimeMillis = 0; // 结束时间
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            //设置通用的请求属性
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            headers.put(FinalUtil.HEADER_CONTENT_TYPE,"application/json;charset=utf-8");
            headers.put(FinalUtil.HEADER_METHOD, "invOpenRetInfoOut");
            conn.setRequestProperty("method", "invOpenRetInfoOut");
            headers.put(FinalUtil.HEADER_INTERFACE_ID, "164");
            conn.setRequestProperty("integration_id", "164");
            headers.put(FinalUtil.HEADER_APP_KEY,appKey);
            conn.setRequestProperty("app_key", appKey);
            headers.put(FinalUtil.HEADER_TIMESTAMP,String.valueOf(MyDateUtil.DateToStr(new Date(), MyDateUtil.formatDefaultTimestamp)));
            conn.setRequestProperty("timestamp", headers.get(FinalUtil.HEADER_TIMESTAMP));
            sign = mySign(headers,token);
            conn.setRequestProperty("sign", sign);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            startTimeMillis = System.currentTimeMillis();
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            logger.info("推送请求参数："+params.toString());
            // 发送请求参数
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            endTimeMillis = System.currentTimeMillis();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            logger.info("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        this.saveLogger(url, params, "", result, startTimeMillis, endTimeMillis,appKey,interfaceid);
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public String sendPost(String url, String appKey, String interfaceid) {
        PrintWriter out = null;
        BufferedReader in = null;
        long startTimeMillis = 0; // 开始时间
        long endTimeMillis = 0; // 结束时间
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            startTimeMillis = System.currentTimeMillis();
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            endTimeMillis = System.currentTimeMillis();
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        this.saveLogger(url, null, "", result, startTimeMillis, endTimeMillis,appKey,interfaceid);
        return result;
    }

    public void saveLogger(String url, JSONObject params, String token, String result, long startTimeMillis,
                           long endTimeMillis,String appKey, String interfaceid) {
        //把推送的日志记录起来  1，推送地址 2，推送参数 3，token 4,推送结果 5，推送开始时间  6，推送结束时间 7，推送状态
        IInterfaceLog iInterfaceLog = new IInterfaceLog();

        iInterfaceLog.setGuid(interfaceLogService.getGuid());//记录 GUID
        if (params != null) {
            iInterfaceLog.setRequestText(params.toString());//请求报文
        }
        iInterfaceLog.setCreatedDate(new Date());
        iInterfaceLog.setUpdateDate(new Date());
        iInterfaceLog.setAppToken(token);//token
        iInterfaceLog.setResponseText(result);//返回报文
        iInterfaceLog.setRequestUrl(url);//访问url
        iInterfaceLog.setCreatedUserGuid(FinalUtil.INTER_FACE_USER_ID);//创建人 GUID
        iInterfaceLog.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);//修改人 GUID
        iInterfaceLog.setStartDate(String.valueOf(startTimeMillis));
        iInterfaceLog.setEndDate(String.valueOf(endTimeMillis));// 结束时间
        iInterfaceLog.setConsumeTime(String.valueOf(endTimeMillis - startTimeMillis));//耗时
        iInterfaceLog.setInterfaceType("callOut");// 调用类型
        iInterfaceLog.setInterfaceApi("支付系统推送");// 接口api
        iInterfaceLog.setInterfaceName("支付系统推送");//接口名称
        iInterfaceLog.setAppName("支付系统推送");//应用系统名称
        iInterfaceLog.setRecallNumber("0");
        iInterfaceLog.setRecallDate(String.valueOf(System.currentTimeMillis()));
        iInterfaceLog.setAppKey(appKey);
        iInterfaceLog.setInterfaceId(interfaceid);
        if (result.contains("0000") || result.contains("成功")  || result.contains("OK")) {
            //推送成功
            iInterfaceLog.setStatus("0");// 接口状态1:失败，0:成功，2:异常
            iInterfaceLog.setErrorcode("0000");// 错误编码
            iInterfaceLog.setErrormsg("处理成功");//错误信息
        } else {
            //推送失败
            JSONObject obj =  JSONObject.fromObject(result);
            iInterfaceLog.setStatus("2");// 接口状态1:失败，0:成功，2:异常
            iInterfaceLog.setErrorcode(String.valueOf(obj.get("code")));// 错误编码
            iInterfaceLog.setErrormsg(String.valueOf(obj.get("msg")));//错误信息
        }
        interfaceLogService.save(iInterfaceLog);
    }
    private String mySign(TreeMap<String, String> headers, String token){
        String mysign = null;
        try {
            mysign = SignCheckUtil.getMySign(headers,token).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mysign;
    }
}
